/*
 * @Author: SailorCai
 * @Date: 2020-12-05 22:58:36
 * @LastEditors: SailorCai
 * @LastEditTime: 2020-12-09 00:08:24
 * @FilePath: /chat/client/src/views/chatList/ChatList.tsx
 */
import "./ChatList.less"
import { List } from 'antd-mobile';
import { useHistory } from 'react-router-dom'
import { useEffect, useState } from 'react'
import { connect } from 'react-redux'
import { getChatList } from '@/api/common'
const Item = List.Item;
const Brief = Item.Brief;

function ChatList (props:any) {
  const history = useHistory();
  const { goChat, msgStatus } = props
  console.log('msgStatus', msgStatus);
  const [chatList, setChatList]:[any[], (u:any) => any] = useState([]);
  const [hall, setHall] = useState({username: '大厅', _id: 'hall'});
  useEffect(() => {
    getList();
    setInterval(getList, 3000)
  }, []);
  async function getList() {
    const res = await getChatList({});
    if (res.code !== 0) return
    setChatList(res.data);
  };
  function itemClick(p: any) {
    console.log(p);
    goChat(p)
    history.push('/chat?id=' + p._id);
  }
  return (
    <div className="chat-list">
      <List>
        <Item extra="10:30" align="top" key="hall" onClick={() => itemClick(hall)} thumb={<Header user={hall} msgStatus={msgStatus.hall} />} multipleLine>
          {hall.username} <Brief>{(msgStatus.hall && msgStatus.hall.latest) || '所有用户将默认在这个群聊'}</Brief>
        </Item>
        {
          chatList.map(user => (
            <Item extra={user.time} key={user._id} align="top" onClick={() => itemClick(user)} thumb={<Header user={user} msgStatus={msgStatus[user._id]} />} multipleLine>
              {user.username} <Brief>{(msgStatus[user._id] && msgStatus[user._id].latest) || '来和我聊天吧'}</Brief>
            </Item>
            ))
        }
      </List>
    </div>
  )
}

function Header(props: any) {
  const { user, msgStatus = {} } = props
  return (
    <div className="chat-thumb">
      <span className="thumb_bg">{user.username}</span>
      {msgStatus.num ? <span className="msg_num">{msgStatus.num}</span> : ''}
    </div>
  )
}

export default connect(
  (state) => ({
    chats: (state as any).hallChat,
    msgStatus: (state as any).msgStatus
  }),
  (dispatch) => {
    return {
      goChat(chator: any) {
        dispatch({type: 'UPDATE_CHATER', payload: chator})
      }
    }
  }
) (ChatList)
